package com.itheima.service.init;

import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.mapper.SetMealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


import java.util.List;

/**
 * @description: 缓存预热, 在初始化bean时就将数据进行储存到redis中
 * @author: wangjingliang
 * @create: 2019-11-14 10:15
 **/
@Component
public class LodeUpdate implements InitializingBean {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CheckItemMapper checkItemMapper;
    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Autowired
    private SetMealMapper setMealMapper;
    /**
     * 在初始化Bean时就进行对数据加载
     *@param: a
     * @return: null
     * @date: 2019/11/14
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("===========从数据库中获取");
        //添加检查项到reids中
        addCheckItemToRedis(redisTemplate,checkItemMapper);
        //添加检查组到redis中
        addCheckGroupToRedis(redisTemplate,checkGroupMapper);
        addSetmealToRedis(redisTemplate,setMealMapper);

    }
   private static void addCheckItemToRedis(RedisTemplate redisTemplate,CheckItemMapper checkItemMapper){

       //查询数据库,获取所有检查项数据
       List<CheckItem> checkItemList = checkItemMapper.selectAll();
       List checkItemList1 = redisTemplate.boundListOps("checkItemList").range(0, -1);
       if (checkItemList1.size()>0||checkItemList1!=null){
           redisTemplate.delete("checkItemList");
       }
       //将集合储存到redis缓存中
       redisTemplate.boundListOps("checkItemList").rightPushAll(checkItemList.toArray());
   }
    private static void addCheckGroupToRedis(RedisTemplate redisTemplate,CheckGroupMapper checkGroupMapper){

        //查询数据库,获取所有检查项数据
        List<CheckGroup> checkGroupList = checkGroupMapper.selectAll();
        List checkItemList1 = redisTemplate.boundListOps("checkGroupList").range(0, -1);
        if (checkItemList1.size()>0||checkItemList1!=null){
            redisTemplate.delete("checkGroupList");
        }
        //将集合储存到redis缓存中
        redisTemplate.boundListOps("checkGroupList").rightPushAll(checkGroupList.toArray());
    }

    private static void addSetmealToRedis(RedisTemplate redisTemplate, SetMealMapper setMealMapper){

        //查询数据库,获取所有检查项数据
        List<Setmeal> setmealList = setMealMapper.selectAll();
        List setmealList1 = redisTemplate.boundListOps("setmealList").range(0, -1);
        if (setmealList1.size()>0||setmealList1!=null){
            redisTemplate.delete("setmealList");
        }
        //将集合储存到redis缓存中
        redisTemplate.boundListOps("setmealList").rightPushAll(setmealList.toArray());
    }
}
